package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.merchant.dto.PositionsDto;
import com.ruoyi.merchant.entity.H002Model;
import com.ruoyi.merchant.entity.Positions;
import com.ruoyi.merchant.service.IPositionsService;
import com.ruoyi.merchant.util.H002ModelCmdEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
public class PositionsServiceImpl implements IPositionsService {


    @Autowired
    private RedisService redisService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Positions> getPositions(String imei) {
        Query condition= new Query();
        //获取24内的坐标位置
        Date prec  = DateUtils.getPreDay(1,new Date());
        condition.addCriteria(Criteria.where("terminalTime").gte(prec));
        condition.addCriteria(Criteria.where("imei").is(imei));
        List<Positions> reportPoliceList = mongoTemplate.find(condition, Positions.class);
        return reportPoliceList;
    }

    @Override
    public PositionsDto getNewPosition(PositionsDto positionsDto) {
        final String s = redisService.getObject(H002ModelCmdEnum.H002Model + positionsDto.getImei());
        H002Model h002Model = JSONObject.parseObject(s, H002Model.class);

        final Date terminalTime = h002Model.getTerminalTime();
        final Date time = Calendar.getInstance().getTime();

        final long time1 = terminalTime.getTime() + 10*60*60*1000;
        final long time2 = time.getTime();

        if (h002Model == null
                || StringUtils.isBlank(h002Model.getLatitude())
                || StringUtils.isBlank(h002Model.getLongitude())
                || time1 > time2
        ){
            return null;
        }
        positionsDto.setLatitude(h002Model.getLatitude());
        positionsDto.setLongitude(h002Model.getLongitude());
        return positionsDto;
    }


}
